import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { OneMapService } from "../one-map.service";
import { MapUiService } from "../map-ui.service";

@Component({
  selector: "app-map-search",
  templateUrl: "./map-search.component.html",
  styleUrls: ["./map-search.component.scss"]
})
export class MapSearchComponent implements OnInit {
  @Output() itemSelect = new EventEmitter();
  searchStream = new Subject<string>();
  searchKey: string = "";
  searchList: any[] = [];
  hideSearch: boolean = false;

  constructor(
    private mapService: OneMapService,
    private mapUiService: MapUiService
  ) {}

  ngOnInit() {
    this.searchStream.pipe(debounceTime(500)).subscribe(searchKey => {
      // console.log("-------" + searchKey);
      this.getSearchList(searchKey);
    });
  }

  onSearch() {
    const searchKey = this.searchKey;
    if (searchKey) {
      this.searchStream.next(searchKey);
    } else {
      this.searchList = [];
    }
  }

  getSearchList(searchKey) {
    this.mapService.getSearchList(searchKey).subscribe(res => {
      console.log(res);
      this.searchList = res["list"];
      this.hideSearch = false;
    });
  }

  onSelect(item) {
    this.searchKey = item.buildName;
    this.hideSearch = true;
    this.itemSelect.emit(item);
  }
}
